<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :minHeight="100"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  // import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './edit-pwd.data';
  // import { postUsers, putUsers } from '/@/api/sys/user';
  // const { createMessage } = useMessage();
  import { useI18n } from '/@/hooks/web/useI18n';
  import { editPatrolPassword } from '/@/api/sys/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStoreWithOut } from '/@/store/modules/user';
  import { MD5 } from 'crypto-js';

  const { t } = useI18n();
  let validatePass2 = ({ values }) => {
    return [
      {
        required: true,
        validator: (_, value) => {
          if (!value) {
            return Promise.reject(t('请确认密码'));
          }
          if (value !== values.password) {
            return Promise.reject('两次输入的密码不一致');
          }
          return Promise.resolve();
        },
      },
    ];
  };

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });
      let userId = 0;
      // let oldUserName: string;
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        console.log(data.record);
        userId = data.record.id;
        setModalProps({ confirmLoading: false });
        setFieldsValue({
          ...data.record,
        });
        // if (!unref(isUpdate)) {
        //   appendSchemaByField(
        //     {
        //       field: 'enterpwd',
        //       label: '确认密码',
        //       component: 'InputPassword',
        //       dynamicRules: validatePass2,
        //     },
        //     'password',
        //   );
        // } else {
        //   removeSchemaByFiled('enterpwd');
        // }
        // updateSchema([
        //   {
        //     field: 'password',
        //     required: !unref(isUpdate),
        //     show: !unref(isUpdate),
        //   },
        // ]);
      });

      const userStore = useUserStoreWithOut();
      const getTitle = '修改密码';
      const { createMessage } = useMessage();
      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);

          editPatrolPassword(userId, {
            ...values,
            password: MD5(values.password).toString(),
            new_password: MD5(values.new_password).toString(),
          }).then(
            () => {
              createMessage.success('修改密码成功, 请重新登录');

              setTimeout(() => {
                // userStore.logout(true);
                closeModal();
              }, 200);
            },
            () => {
              // 业务层不提示了
              // createMessage.error('添加用户失败');
            },
          );
        } catch (e) {
          console.log(e);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit, t };
    },
  });
</script>
